from fastapi import APIRouter, Depends
from app.api.schemas.token import Token
from app.api.schemas.user import User_Schema
from typing import Dict, Optional
from app.db.crud import get_db
from sqlalchemy.orm import Session
from datetime import timedelta
from app.setting.setting import config
from app.common.security import create_token
from app.common.response_code import resp_200, resp_202
from app.db.crud.user_crud import get_user, check_user

loginAPI = APIRouter()

# 登录接口，获取token接口和登录接口合并
@loginAPI.post("/login", response_model=Token, summary="用户登录认证接口")
def login(login_user: Dict, db: Session=Depends(get_db)):
    # 根据用户名和密码查询用户
    res = check_user(login_user, db)
    # 如果登录校验不通过，返回错误信息
    if not res["user"]:
        return resp_202(login_user['login_name'], message=res["message"])
    
    # 校验通过，返回token
    # 设置token过期时间
    access_token_expires = timedelta(minutes=config.ACCESS_TOKEN_EXPIRE_MINUTES)
    # 把username加密
    access_token = create_token(
        data={"sub": login_user['login_name']}, expires_delta=access_token_expires
    )
    token = Token(login_name = login_user['login_name'], access_token=access_token)

    return resp_200(token, message="登录成功")

@loginAPI.post("/test", summary="测试部署用")
def test(postchar: str):
    return resp_200(postchar, message="测试成功")